package com.Hsu.book.interceptor;

import com.Hsu.book.constant.Constants;
import com.Hsu.book.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Hsu琛君珩
 * @ClassName:LoginInterceptor
 * @date 2024-01-07
 * @apiNote
 * @Version: v1.0
 */

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("登录拦截器校验...");
        //返回true表示放行，返回false表示拦截
        //检验用户是否登录
        //HttpSession session=request.getSession(false);//true表示没有session就创建一个，false表示没有就直接返回
        //if(session!=null||session.getAttribute(Constants.SESSION_USER_KEY)!=null){
        //    UserInfo userInfo= (UserInfo) session.getAttribute(Constants.SESSION_USER_KEY);
        //    if(userInfo!=null&&userInfo.getId()>=0){
        //        return true;//放行
        //    }
        //}
        HttpSession session = request.getSession(true);//true表示没有session就创建一个，false表示没有就直接返回
        UserInfo userInfo = (UserInfo) session.getAttribute(Constants.SESSION_USER_KEY);
        if (userInfo != null && userInfo.getId() >= 0) {
            return true;//放行
        }
        response.setStatus(401);//401表示未认证登录
        return false;//拦截
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("目标方法执行后");
    }
}
